
import urllib.request


def load_baidu():


    url = "http://www.baidu.com/"

    #添加请求头
    header = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
    }


    #创建请求对象
    request = urllib.request.Request(url,headers=header)

    # 动态的添加headers
    # request.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36')

    #请求网络数据
    response = urllib.request.urlopen(request)
    data = response.read().decode('utf-8')


    #响应头
    # print(response.headers)

    #获取请求头的信息
    # print(request.headers)
    # print(request.get_header('User-agent'))


    #获取到完整的url
    get_url = request.get_full_url()
    print(get_url)  #http://www.baidu.com/


    #写入文件
    # with open('02header.html',mode='w',encoding='utf-8') as f:
    #     f.write(data)

load_baidu()